﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.Identity;
using TomNet.IMSC.Core.Contracts.LowPriceHouse;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.Common;
using TomNet.IMSC.Model.DbModels.LowPriceHouse;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.LowPriceHouse.Controllers
{
    [Description("低价房")]
    public class LowPriceHouseController : BaseController
    {
        public ILowPriceHousesContract LowPriceHousesContract { get; set; }
        public ILowPriceHouseBuildingsContract LowPriceHouseBuildingsContract { get; set; }
        public IAreaContract AreaContract { set; get; }
        public IStaffContract StaffContract { get; set; }
        public IOwnerContract OwnerContract { get; set; }
        public IDictionaryContract DictionaryContract { get; set; }  
        public IImagesContract ImagesContract { get; set; }
        public IAgentContract AgentContract { get; set; }
        public IImageGroupContract ImageGroupContract { get; set; }
        public IStaffRolesContract StaffRolesContract { get; set; }
        public IRoleContract RoleContract { get; set; }
        public IBuildingTopContract BuildingTopContract { get; set; }
        #region 低价房列表 
        [Description("低价房-列表")]
        public ActionResult LowPriceHouseListIndex(int GroupID = 1)
        {
            ViewBag.GroupID = GroupID;
            return View();
        }
        [HttpPost]
        public ActionResult LowPriceHouseListIndexAsync(int pageIndex, int pageSize, string search = "", string Province = "", string City = "", string District = "", string State = "", string LowHouseType = "", int GroupID = 1)
        {
            var mvc = LowPriceHousesContract.TrackEntities.ToList();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            var agentid = model.AgentId;
            var state = Convert.ToInt32(State);
            var type = Convert.ToInt32(LowHouseType);
            var query = from a in LowPriceHousesContract.TrackEntities
                        join b in LowPriceHouseBuildingsContract.TrackEntities
                        on a.LowPriceHouseBuildingID equals b.Id
                        where (!a.IsDeleted && a.GroupID == GroupID)
                        select new
                        {
                            Id = a.Id,
                            //省
                            ProvinceID = b.ProvinceID,
                            //市
                            CityID = b.CityID,
                            //区
                            AreaID = b.AreaID,
                            //小区ID
                            LowPriceHouseBuildingID = b.Name,
                            //门牌号
                            HouseNumber = a.HouseNumber,
                            //原价
                            CostPrice = a.CostPrice,
                            //底价
                            LowPrice = a.LowPrice,
                            //协议价
                            NegotiatedPrice = a.NegotiatedPrice,
                            //价格条件(字典)
                            PriceCondition = a.PriceCondition,
                            //手续费
                            Poundage = a.Poundage,
                            //佣金说明
                            Brokerage = a.Brokerage,
                            //佣金数额
                            BrokerageAmount = a.BrokerageAmount,
                            //带看佣金
                            BandSawBrokerage = a.BandSawBrokerage,
                            //佣金帐期
                            CommissionAccount = a.CommissionAccount,
                            //奖励说明
                            AwardDescription = a.AwardDescription,
                            //规则
                            Rules = a.Rules,
                            //能否贷款
                            IsLoan = a.IsLoan == 1 ? "能" : "不能",
                            //贷款规则
                            LoanRules = a.LoanRules,
                            //首付比例
                            DownPaymentRate = a.DownPaymentRate,
                            //建筑面积
                            Area = a.Area,
                            //使用面积
                            UseArea = a.UseArea,
                            //户型
                            HouseType = a.HouseType,
                            //户型说明
                            HouseTypeRemark = a.HouseTypeRemark,
                            //室数
                            RoomNumber = a.RoomNumber,
                            //厅数
                            HallNumber = a.HallNumber,
                            //卫生间数
                            ToiletNumber = a.ToiletNumber,
                            //厨房数
                            CookNumber = a.CookNumber,
                            //阳台数
                            BalconyNumber = a.BalconyNumber,
                            //设施
                            Installation = a.Installation,
                            //性质(字典)
                            Nature = a.Nature,
                            //住宅类别(字典选)
                            ResidenceType = a.ResidenceType,
                            //房屋类型(字典选)
                            BuildingsType = a.BuildingsType,
                            //建筑结构
                            BuildingClass = a.BuildingClass,
                            //装修状况(字典)
                            DecorationCondition = a.DecorationCondition,
                            //产权年限
                            PropertyRight = a.PropertyRight,
                            //产权类型
                            PropertyType = a.PropertyType,
                            //建造年代
                            CreateYear = a.CreateYear,
                            //楼层
                            Storey = a.Storey,
                            //总楼层
                            TotalStorey = a.TotalStorey,
                            //朝向(字典选)
                            Orientations = a.Orientations,
                            //星标
                            StarTarget = a.StarTarget == "" ? "0" : a.StarTarget,
                            //星标备注
                            StarTargetRemark = a.StarTargetRemark,
                            //状态
                            State = a.State,
                            //备注
                            Remark = a.Remark,
                            //代理
                            AgentID = a.AgentID,
                            //提供人员 
                            MediumOfCommunicationStaffID = (from m in StaffContract.TrackEntities where m.IsDeleted == false && m.Id == a.MediumOfCommunicationStaffID select m.Name).FirstOrDefault(),
                            //维护人员
                            StationedStaffID = (from m in StaffContract.TrackEntities where m.IsDeleted == false && m.Id == a.StationedStaffID select m.Name).FirstOrDefault(),
                            //房主
                            OwnerID = (from m in OwnerContract.TrackEntities where m.IsDeleted == false && m.Id == a.OwnerID select m.Name).FirstOrDefault(),
                            //更名期限
                            ReNameDeadline = a.ReNameDeadline,
                            //类型  1住宅  2旅游地产  3门市   4商铺
                            LowHouseType = a.LowHouseType,
                            //上线日期
                            UpTime = a.UpTime,
                            
                            IsLocked = a.IsLocked,
                            IsDeleted = a.IsDeleted,
                            LowPriceCreatedTime = a.CreatedTime,
                            //利润
                            Profit = a.LowPrice - a.NegotiatedPrice - a.BrokerageAmount,

                            BuildingTopId = (from btc in BuildingTopContract.Entities where btc.UnionModule == 2 && a.Id == btc.UnionID && !btc.IsDeleted select btc.Id).FirstOrDefault(),
                            BeginTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 2 && a.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.BeginTime).FirstOrDefault(),
                            EndTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 2 && a.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.EndTime).FirstOrDefault(),
                            ShowIndex = (from btc in BuildingTopContract.Entities where btc.UnionModule == 2 && a.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.ShowIndex).FirstOrDefault(),
                            CreatedTime = (from btc in BuildingTopContract.Entities where btc.UnionModule == 2 && a.Id == btc.UnionID && !btc.IsDeleted && btc.BeginTime < DateTime.Now && btc.EndTime > DateTime.Now select btc.CreatedTime).FirstOrDefault(),
                        };
            
            if (!string.IsNullOrWhiteSpace(search))
            {
                query = query.Where(m => m.HouseNumber.Contains(search) || m.LowPriceHouseBuildingID.Contains(search));
            }
            if (agentid != 0)
            {
                query = query.Where(m => m.AgentID == agentid);
            }
            if (!string.IsNullOrWhiteSpace(Province))
            {
                query = query.Where(m => m.ProvinceID.Contains(Province));
            }
            if (!string.IsNullOrWhiteSpace(City))
            {
                query = query.Where(m => m.CityID.Contains(City));
            }
            if (!string.IsNullOrWhiteSpace(District))
            {
                query = query.Where(m => m.AreaID.Contains(District));
            }
            if (state != -1)
            {
                query = query.Where(m => m.State == state);
            }
            if (type != 0)
            {
                query = query.Where(m => m.LowHouseType == type);
            }

            var total = query.Count();

            //默认给一个排序的字段 
            var topCount = BuildingTopContract.Entities.Where(m => m.UnionModule == 2).Count();
            if (topCount > 0)
            {
                query = query.OrderByDescending(m => m.ShowIndex).ThenByDescending(m => m.BeginTime).ThenByDescending(m => m.Id);
            }
            else
            {
                query = query.OrderByDescending(m => m.Id);
            }

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 低价房添加
        [Description("低价房-添加")]
        public ActionResult LowPriceHouseListInsert(int GroupID = 1)
        {
            ViewBag.GroupID = GroupID;
            intorcount();
            return View();
        }
        [HttpPost]
        public ActionResult LowPriceHouseListInsertAsync(LowPriceHouses entity)
        {
            //var InstallationString = "";
            DateTime now = DateTime.Now;
            //星标
            entity.StarTarget = "0";
            //状态
            entity.State = 1;
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;
            #region 赋值""
            if (entity.HouseNumber == null)
            {
                entity.HouseNumber = "";
            }
            if (entity.PriceCondition == null)
            {
                entity.PriceCondition = "";
            }
            if (entity.Poundage == null)
            {
                entity.Poundage = "";
            }
            if (entity.Brokerage == null)
            {
                entity.Brokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.Rules == null)
            {
                entity.Rules = "";
            }
            if (entity.LoanRules == null)
            {
                entity.LoanRules = "";
            }
            if (entity.HouseType == null)
            {
                entity.HouseType = "";
            }
            if (entity.HouseTypeRemark == null)
            {
                entity.HouseTypeRemark = "";
            }
            if (entity.Installation == null)
            {
                entity.Installation = "";
            }
            if (entity.Nature == null)
            {
                entity.Nature = "";
            }
            if (entity.ResidenceType == null)
            {
                entity.ResidenceType = "";
            }
            if (entity.BuildingsType == null)
            {
                entity.BuildingsType = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.PropertyType == null)
            {
                entity.PropertyType = "";
            }
            if (entity.CreateYear == null)
            {
                entity.CreateYear = "";
            }
            if (entity.Orientations == null)
            {
                entity.Orientations = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.ReNameDeadline == null)
            {
                entity.ReNameDeadline = "";
            }
            #endregion
            //设施
            var InstallationCount = Request["Installation"];
            entity.Installation = InstallationCount;
            try
            {
                var query = LowPriceHousesContract.CheckExists(m => m.LowPriceHouseBuildingID.Equals(entity.LowPriceHouseBuildingID) && m.HouseNumber == entity.HouseNumber && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的房源";
                }
                else
                {
                    var count = LowPriceHousesContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 低价房修改 
        [Description("低价房-修改")]
        public ActionResult LowPriceHouseListEdit(int id)
        {
            var entity = LowPriceHousesContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");
            ViewData["entity"] = entity;
            //设施
            var Installation = entity.Installation;
            if (Installation != null && Installation != "")
            {
                var InstallationList = Installation.Split(',');
                ViewBag.InstallationList = InstallationList;
            }
            intorcount();
            return View();
        }
        [HttpPost]
        public ActionResult LowPriceHouseListEditAsync(LowPriceHouses entity)
        {
            //var InstallationString = "";
            DateTime now = DateTime.Now;
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.AgentID = model.AgentId;
            #region 赋值""
            if (entity.HouseNumber == null)
            {
                entity.HouseNumber = "";
            }
            if (entity.PriceCondition == null)
            {
                entity.PriceCondition = "";
            }
            if (entity.Poundage == null)
            {
                entity.Poundage = "";
            }
            if (entity.Brokerage == null)
            {
                entity.Brokerage = "";
            }
            if (entity.BandSawBrokerage == null)
            {
                entity.BandSawBrokerage = "";
            }
            if (entity.CommissionAccount == null)
            {
                entity.CommissionAccount = "";
            }
            if (entity.AwardDescription == null)
            {
                entity.AwardDescription = "";
            }
            if (entity.Rules == null)
            {
                entity.Rules = "";
            }
            if (entity.LoanRules == null)
            {
                entity.LoanRules = "";
            }
            if (entity.HouseType == null)
            {
                entity.HouseType = "";
            }
            if (entity.HouseTypeRemark == null)
            {
                entity.HouseTypeRemark = "";
            }
            if (entity.Installation == null)
            {
                entity.Installation = "";
            }
            if (entity.Nature == null)
            {
                entity.Nature = "";
            }
            if (entity.ResidenceType == null)
            {
                entity.ResidenceType = "";
            }
            if (entity.BuildingsType == null)
            {
                entity.BuildingsType = "";
            }
            if (entity.BuildingClass == null)
            {
                entity.BuildingClass = "";
            }
            if (entity.DecorationCondition == null)
            {
                entity.DecorationCondition = "";
            }
            if (entity.PropertyRight == null)
            {
                entity.PropertyRight = "";
            }
            if (entity.PropertyType == null)
            {
                entity.PropertyType = "";
            }
            if (entity.CreateYear == null)
            {
                entity.CreateYear = "";
            }
            if (entity.Orientations == null)
            {
                entity.Orientations = "";
            }
            if (entity.StarTarget == null)
            {
                entity.StarTarget = "";
            }
            if (entity.StarTargetRemark == null)
            {
                entity.StarTargetRemark = "";
            }
            if (entity.Remark == null)
            {
                entity.Remark = "";
            }
            if (entity.ReNameDeadline == null)
            {
                entity.ReNameDeadline = "";
            }
            #endregion
            //设施
            var InstallationCount = Request["Installation"];
            entity.Installation = InstallationCount;
            try
            {
                var query = LowPriceHousesContract.CheckExists(m => m.LowPriceHouseBuildingID == entity.LowPriceHouseBuildingID && m.HouseNumber == entity.HouseNumber && m.Id != entity.Id && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的房源";
                }
                else
                {
                    var count = LowPriceHousesContract.Update(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 低价房删除
        [Description("低价房-删除")]
        [HttpPost]
        public ActionResult LowPriceHouseListDeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                LowPriceHousesContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new LowPriceHouses { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 克隆
        public ActionResult Clone(string ids)
        {
            var result = new AjaxResult();
            try
            {

                //开始事务
                LowPriceHousesContract.Repository.UnitOfWork.BeginTransaction();

                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                for (int i = 0; i < idsInt.Length; i++)
                {
                    LowPriceHouses lph = new LowPriceHouses();
                    var entity = LowPriceHousesContract.GetByKey(idsInt[i]);
                    //查询图片
                    var InterfixID = entity.Id;
                    var ImageEntity = ImagesContract.Entities.Where(m => m.InterfixID == InterfixID && m.GroupID == 4).ToList();
                    #region 赋值Model
                    lph.OldID = entity.OldID;
                    lph.LowPriceHouseBuildingID = entity.LowPriceHouseBuildingID;
                    lph.HouseNumber = entity.HouseNumber;
                    lph.CostPrice = entity.CostPrice;
                    lph.LowPrice = entity.LowPrice;
                    lph.NegotiatedPrice = entity.NegotiatedPrice;
                    lph.PriceCondition = entity.PriceCondition;
                    lph.Poundage = entity.Poundage;
                    lph.Brokerage = entity.Brokerage;
                    lph.BrokerageAmount = entity.BrokerageAmount;
                    lph.BandSawBrokerage = entity.BandSawBrokerage;
                    lph.CommissionAccount = entity.CommissionAccount;
                    lph.AwardDescription = entity.AwardDescription;
                    lph.Rules = entity.Rules;
                    lph.IsLoan = entity.IsLoan;
                    lph.LoanRules = entity.LoanRules;
                    lph.DownPaymentRate = entity.DownPaymentRate;
                    lph.Area = entity.Area;
                    lph.UseArea = entity.UseArea;
                    lph.HouseType = entity.HouseType;
                    lph.HouseTypeRemark = entity.HouseTypeRemark;
                    lph.RoomNumber = entity.RoomNumber;
                    lph.HallNumber = entity.HallNumber;
                    lph.ToiletNumber = entity.ToiletNumber;
                    lph.CookNumber = entity.CookNumber;
                    lph.BalconyNumber = entity.BalconyNumber;
                    lph.Installation = entity.Installation;
                    lph.Nature = entity.Nature;
                    lph.ResidenceType = entity.ResidenceType;
                    lph.BuildingsType = entity.BuildingsType;
                    lph.BuildingClass = entity.BuildingClass;
                    lph.DecorationCondition = entity.DecorationCondition;
                    lph.PropertyRight = entity.PropertyRight;
                    lph.PropertyType = entity.PropertyType;
                    lph.CreateYear = entity.CreateYear;
                    lph.Storey = entity.Storey;
                    lph.TotalStorey = entity.TotalStorey;
                    lph.Orientations = entity.Orientations;
                    lph.StarTarget = entity.StarTarget;
                    lph.StarTargetRemark = entity.StarTargetRemark;
                    lph.ShowIndex = entity.ShowIndex;
                    lph.State = entity.State;
                    lph.Remark = entity.Remark;
                    lph.AgentID = entity.AgentID;
                    lph.MediumOfCommunicationStaffID = entity.MediumOfCommunicationStaffID;
                    lph.StationedStaffID = entity.StationedStaffID;
                    lph.OwnerID = entity.OwnerID;
                    lph.ReNameDeadline = entity.ReNameDeadline;
                    lph.LowHouseType = entity.LowHouseType;
                    lph.GroupID = entity.GroupID;
                    lph.UpTime = entity.UpTime;
                    #endregion
                    LowPriceHousesContract.Insert(lph);
                    var NewId = lph.Id;
                    foreach (var itemImg in ImageEntity)
                    {
                        //生成新文件名
                        string SavePath = Server.MapPath(itemImg.ImagePath);

                        string NewFileName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + Path.GetExtension(itemImg.FileName);
                        while (System.IO.File.Exists(SavePath + NewFileName))
                        {
                            System.Threading.Thread.Sleep(1);
                            NewFileName = DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + Path.GetExtension(itemImg.FileName);
                        }

                        //复制图片文件
                        System.IO.File.Copy(SavePath + itemImg.FileName, SavePath + NewFileName);

                        //写入数据库
                        var Image = ImagesContract.GetByKey(itemImg.Id);
                        Images img = new Images();
                        img.GroupID = 4;
                        img.InterfixID = NewId;
                        img.ImageType = Image.ImageType;
                        img.ImagePath = Image.ImagePath;
                        img.FileName = NewFileName;
                        img.ShowIndex = Image.ShowIndex;
                        img.Tag = Image.Tag;
                        img.Remark = Image.Remark;

                        ImagesContract.Insert(img);


                    }

                }

                result.Type = AjaxResultType.Success;
                result.Content = "克隆成功";
                //if (count > 0)
                //{
                //    result.Type = AjaxResultType.Success;
                //    result.Content = "克隆成功";
                //}
                //else
                //{
                //    result.Type = AjaxResultType.Error;
                //    result.Content = "克隆失败";
                //}
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            //结束事务
            LowPriceHousesContract.Repository.UnitOfWork.Commit();

            return JsonEx(result);
        }
        #endregion

        #region 设置状态
        /// <summary>
        /// 设置在线状态
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Description("楼盘-设置状态")]
        public ActionResult StateSet(int id)
        {

            if (id == 0) throw new Exception("参数错误");
            var entity = LowPriceHousesContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            ViewBag.entity = entity;
            return View();
        }
        [HttpPost]
        public ActionResult EditStateSet(LowPriceHouses entity)
        {
            var result = new AjaxResult();
            try
            {
                var count = LowPriceHousesContract.UpdateDirect(d => entity.Id == d.Id, d => new LowPriceHouses { State = entity.State });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion

        #region 设置结算模式
        /// <summary>
        /// 设置结算模式
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns> 
        [Description("楼盘-设置结算模式")]
        public ActionResult SetStarTarget(int id)
        {

            if (id == 0) throw new Exception("参数错误");
            var entity = LowPriceHousesContract.GetByKey(id);
            if (entity == null) throw new Exception("未找到该记录");
            ViewBag.entity = entity;
            return View();
        }
        /// <summary>
        /// 设置结算模式
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditSetStarTarget(LowPriceHouses entity)
        {
            var result = new AjaxResult();
            try
            {
                var count = LowPriceHousesContract.UpdateDirect(d => entity.Id == d.Id,
                    d => new LowPriceHouses { StarTarget = entity.StarTarget, StarTargetRemark = entity.StarTargetRemark });
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }

            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }

            return JsonEx(result);
        }
        #endregion

        #region 下拉框传值 
        public void intorcount()
        {
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            //小区 
            List<SelectListItem> gridData = new List<SelectListItem>();
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            var data = from dic in LowPriceHouseBuildingsContract.TrackEntities
                       select new SelectListItem
                       {
                           Value = dic.Id + "",
                           Text = dic.Name
                       };
            gridData.AddRange(data);
            ViewData["LowPriceHouseBuildingID"] = new SelectList(gridData);

            //渠道人员
            var channel = from s in StaffContract.Entities
                          where s.AgentID == model.AgentId && s.IsDeleted == false
                          select new
                          {
                              StaffID = s.Id,
                              StaffName = s.Name,
                          };
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from c in channel
                   select new SelectListItem
                   {
                       Value = c.StaffID + "",
                       Text = c.StaffName
                   };
            gridData.AddRange(data);
            ViewData["channel"] = new SelectList(gridData);
            //驻场人员
            var inThefield = from s in StaffContract.Entities
                             where StaffRolesContract.Entities.Count(m => m.RoleID == 12 && s.Id == m.StaffID) > 0 && s.AgentID == model.AgentId && s.IsDeleted == false
                             select new
                             {
                                 StaffID = s.Id,
                                 StaffName = s.Name,
                             };
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from c in inThefield
                   select new SelectListItem
                   {
                       Value = c.StaffID + "",
                       Text = c.StaffName
                   };
            gridData.AddRange(data);
            ViewData["inThefield"] = new SelectList(gridData);


            //房主 
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in OwnerContract.TrackEntities.Where(m => !m.IsDeleted)
                   select new SelectListItem
                   {
                       Value = dic.Id + "",
                       Text = dic.Name + "：" + dic.Phone
                   };
            gridData.AddRange(data);
            ViewData["OwnerID"] = new SelectList(gridData);
            //住宅类别
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "ResidenceType")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["ResidenceType"] = new SelectList(gridData);
            //房屋类别
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "BuildingsType")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["BuildingsType"] = new SelectList(gridData);
            //朝向
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "Orientations")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["Orientations"] = new SelectList(gridData);
            //建筑结构
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "BuildingClass")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["BuildingClass"] = new SelectList(gridData);
            //产权类型
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "PropertyType")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["PropertyType"] = new SelectList(gridData);
            //价格条件 
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "PriceCondition")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["PriceCondition"] = new SelectList(gridData);
            //楼盘性质 
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "Nature")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["Nature"] = new SelectList(gridData);
            //装修状况
            gridData = new List<SelectListItem>();
            gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "DecorationCondition")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["DecorationCondition"] = new SelectList(gridData);
            //设施
            gridData = new List<SelectListItem>();
            //gridData.Add(new SelectListItem { Value = "0", Text = "无" });
            data = from dic in DictionaryContract.TrackEntities.Where(m => m.Name == "Installation")
                   select new SelectListItem
                   {
                       Value = dic.Value,
                       Text = dic.Value
                   };
            gridData.AddRange(data);
            ViewData["Installation"] = new SelectList(gridData);
        }
        #endregion

        #region 获取省属区
        /// <summary>  
        /// 获取省份  
        /// </summary>  
        [AjaxOnly]
        public ActionResult GetProvincelist()
        {
            //获取省份数据   
            var queryResult = AreaContract.TrackEntities.Where(a => a.AreaLevel == 1);
            return JsonEx(queryResult.ToList(), JsonRequestBehavior.AllowGet);
        }
        /// <summary>  
        /// 获取城市  
        /// </summary>  
        /// <param name="pid"></param>  
        /// <returns></returns>  
        [AjaxOnly]
        public ActionResult GetCitylist(string pid)//根据省份ID获取城市  
        {
            pid = pid.Trim();
            var list = AreaContract.TrackEntities.Where(m => m.ParentID.Equals(pid)).ToList();//城市ID对应值  
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        [AjaxOnly]
        /// <summary>  
        /// 获取区
        /// </summary>  
        /// <param name="cid"></param>  
        /// <returns></returns>  
        public ActionResult GetDistrictlist(string cid)//根据城市ID获取区县ID  
        {
            cid = cid.Trim();
            var list = AreaContract.TrackEntities.Where(a => a.ParentID.Equals(cid)).ToList();//区县ID对应值 
            return JsonEx(list, JsonRequestBehavior.AllowGet);
        }
        #endregion
         
        #region 置顶
        [Description("楼盘-置顶")]
        public ActionResult EditTopData(int UnionModule, int UnionID, int BuildingTopID)
        {
            ViewBag.UnionModule = UnionModule;
            ViewBag.UnionID = UnionID;
            if (BuildingTopID != 0)
            {
                var topEntity = BuildingTopContract.GetByKey(BuildingTopID);
                ViewBag.topEntity = topEntity;
            }
            else
            {
                var bt = new BuildingTop();
                bt.Id = 0;
                bt.UserID = 0;
                bt.UnionID = UnionID;
                bt.UnionModule = UnionModule;
                bt.BeginTime = DateTime.Now;
                bt.EndTime = DateTime.Now;
                bt.TopType = 0;
                bt.ShowIndex = 1;
                ViewBag.topEntity = bt;
            }
            return View();
        }
        [HttpPost]
        public ActionResult EditTopDataAsync(BuildingTop entity)
        {
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            if (entity.Id == 0)
            {
                entity.UserID = model.Id;
                //新增
                var count = BuildingTopContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            else
            {
                var BuildingTopModel = BuildingTopContract.GetByKey(entity.Id);
                BuildingTopModel.UserID = model.Id;
                BuildingTopModel.BeginTime = entity.BeginTime;
                BuildingTopModel.EndTime = entity.EndTime;
                BuildingTopModel.TopType = entity.TopType;
                BuildingTopModel.ShowIndex = entity.ShowIndex;
                var count = BuildingTopContract.Update(BuildingTopModel);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }

            return JsonEx(result);
        }
        #endregion
    }
}